package com.example.contentserver.Provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.example.contentserver.database.UserDBHelper;
import com.example.contentserver.pojo.UserInfoContent;

public class UserInfoProvider extends ContentProvider {
    UserDBHelper mDBHelper=null;
    private static final UriMatcher URI_MATCHER=new UriMatcher(UriMatcher.NO_MATCH);
    private static final int USERS=1;
    private static final int USER=2;

    static {
        URI_MATCHER.addURI(UserInfoContent.AUTHORITIES,"/user",USERS);
        URI_MATCHER.addURI(UserInfoContent.AUTHORITIES,"/user/#",USER);
    }

    public UserInfoProvider() {
    }

    @Override
    public boolean onCreate() {
        mDBHelper=UserDBHelper.getInstance(getContext());
        Log.d("tang", "UserInfoProvider:onCreate");
        //返回false表示实例化成功了，true表示实例化失败
        return true;
    }
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase wDB = mDBHelper.getWritableDatabase();
        int count=0;
        switch (URI_MATCHER.match(uri))
        {
            case USERS:
                count =wDB.delete(UserDBHelper.TABLE_NAME,selection,selectionArgs);
                break;
            case USER:
//                String id=uri.getLastPathSegment();
//                count =wDB.delete(UserDBHelper.TABLE_NAME,"_id=?",new String[]{id});
                String name=uri.getLastPathSegment();
                count =wDB.delete(UserDBHelper.TABLE_NAME,"name=?",new String[]{name});
        }
        wDB.close();

        return count;
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase wDB = mDBHelper.getWritableDatabase();
        wDB.insert(mDBHelper.TABLE_NAME,null,values);
        return uri;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase rDB = mDBHelper.getReadableDatabase();
        return rDB.query(mDBHelper.TABLE_NAME,null,selection,selectionArgs,null,null,sortOrder,null);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}